<?php

declare(strict_types=1);

namespace App\Controller\Home\User;

use App\Model\ChargeOption;
use App\Model\Device;
use App\Model\Service;
use App\Model\Station;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;

class UserDeviceController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;

    #[Inject]
    protected Station $station;

    #[Inject]
    protected ChargeOption $chargeOption;

    #[Inject]
    protected Distributors $distributors;

    #[Inject]
    protected Device $device;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**
     * 设备详情
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function detail(RequestInterface $request):ResponseInterface{
        try {
            $sn = $request->input('sn');
            $sn = trim($sn);
            if(!$sn){
                return $this->error(1001,'设备不存在');
            }
            $data = $this->device->where('sn',$sn)
                ->with(['port', 'station:id,name,address,distributor_id,lat,lng,is_service']) // 同时加载 port 和 station
                ->first();
            if(!$data){
                return $this->error(1001,'设备不存在');
            }
            return $this->success($data);
        } catch (\Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(500,$e->getMessage());
        }
    }


    /**
     * 获取设备号套餐
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function getCharge(RequestInterface $request):ResponseInterface{
        try {
            $sn =$request->input('sn',0,'int');
            if(is_string($sn)){
                $sn = trim($sn);
            }
            if(!$sn){
                return $this->error(1001,'设备不存在');
            }
            $device = $this->device->where('sn',$sn)->
                with('station')->first();
            if(!$device || !$device->station){
                return $this->error(1001,'电站信息不存在');
            }
            if(!$device->station->charge_id){
                return $this->error(1001,'电站暂未设定套餐');
            }
            $charge = ChargeOption::where('id',$device->station->charge_id)
                ->with('time_children','power_children','service_children')
                ->first();
            if(!$charge){
                return $this->error(1001,'设备暂无可用套餐');
            }
            return $this->success($charge);
        } catch (\Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(500, $e->getMessage());
        }
    }

    /**获取客服电话和二维码
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getService(RequestInterface $request):ResponseInterface{
        try {
            $station_id = $request->input('station_id');
            if(!$station_id){
                return $this->error();
            }
            $distributor_id = $this->station->where('id',$station_id)->value('distributor_id');
            $distributor = $this->distributors->where('id',$distributor_id)->first(['customer_service_phone','service_image']);
            return $this->success($distributor);
        } catch (\Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(500, $e->getMessage());
        }
    }


    /**服务列表
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function serviceList(RequestInterface $request):ResponseInterface
    {
        $data['list'] = Service::orderBy('days', 'desc')
            ->get()->toArray();
        $data['total']= Service::count();
        return $this->success($data);
    }


    /**二维码重定向
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function qrCodeParse(RequestInterface $request){
        $sn = $request->input('sn');
        $sn = trim($sn);
        $response = container()->get(\Hyperf\HttpServer\Contract\ResponseInterface::class);
        // 获取 User-Agent 判断访问来源
        $userAgent = $request->header('user-agent', '');

        $isWeChat = stripos($userAgent, 'micromessenger') !== false;
        // 检测是否为支付宝环境
        $isAlipay = stripos($userAgent, 'alipayclient') !== false;

        if ($isWeChat || $isAlipay) {
          //  Normal::logger('w-userAgent:'.$userAgent,'home');
            // 微信环境：跳转小程序落地页
            $url = Common::MAIN_HOST . '/pages/equipment-detail-user/index?sn=' . $sn;
        } else {
         //   Normal::logger('pc-userAgent:'.$userAgent,'home');
            // 非微信环境：跳转PC管理后台
            $url = Common::MAIN_HOST . '/admin/index.html';
        }

        return $response->redirect($url);
    }

    public function qrCodeDistributor(RequestInterface $request){
        $type = $request->input('type');
        $prod = $request->input('envVersion','trial');
        $response = container()->get(\Hyperf\HttpServer\Contract\ResponseInterface::class);
        $url = Common::MAIN_HOST.'/pages/home/index/?type='.$type.'&wechat_miniprogram_env='.$prod;
        return $response->redirect($url);
    }


    /**获取附近电站
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getNearDevice(RequestInterface $request)
    {
        try {
            $lat = $request->input('lat');
            $lng = $request->input('lng');
            $distance = $request->input('distance', 2); // 默认距离为2公里
            $list = Device::queryNearbyStations((float)$lng, (float)$lat, (float)$distance);
            $data = [];
            foreach ($list as $k => &$v) {
                $v['station'] = Station::where('id', $v[0])->where('is_active', 1)
                    ->withCount('device')
                    // 正确统计使用中和空闲端口数量
                    ->withCount(['device as use_port_count' => function($query) {
                        $query->join('device_port', 'devices.id', '=', 'device_port.device_id')
                            ->where('device_port.status', 1);
                    }])
                    ->withCount(['device as free_port_count' => function($query) {
                        $query->join('device_port', 'devices.id', '=', 'device_port.device_id')
                            ->where('device_port.status', 0);
                    }])
                    ->first();
                if(!$v['station']){
                    unset($list[$k]);
                }else{
                    if($v['station']->device_count <= 0){
                        unset($list[$k]);
                    }else{
                        $data[] = $v;
                    }
                }
            }
            usort($data, function($a, $b) {
                return $a[1] <=> $b[1];
            });

            return $this->success($data);
        } catch (\Exception $e) {
            Normal::logger($e->getMessage() . $e->getTraceAsString(), 'home');
            return $this->error(500, $e->getMessage());
        }
    }




    public function getDeviceList(RequestInterface $request){
        $station_id = $request->input('station_id');
        $devices = $this->device->where('station_id', $station_id)
            ->with('port')
            ->get();
        $data['inline'] = $devices->where('inline', 1)->values();
        $data['offline'] = $devices->where('inline', 0)->values();
        $data['detail'] = $this->station->where('id', $station_id)->first();

        return $this->success($data);
    }
}
